<?php
/**
 * Created by PhpStorm.
 * User: Neho
 * Date: 2018/2/23
 * Time: 10:36
 */

namespace app\common\model;

use think\Db;
use think\Model;

class UserCart extends Model
{
    public function updateNum($num, $productId, $cartId)
    {
        $this->startTrans();
        try {
            $productResult = Db::execute('update em_goods_product set product_stock = product_stock - ? where product_stock >= ? and id = ?', [$num, $num, $productId]);
            if ($productResult) {
                $cartResult = Db::execute('update em_user_cart set product_num = product_num + ? where id = ?', [$num, $cartId]);
                if ($cartResult) {
                    $this->commit();
                    return true;
                }
            }
        } catch (\Exception $e) {
            $this->rollback();
        }
    }

    public function productList($ids)
    {
        $list = Db::table('em_user_cart')
            ->field('a.id as carId, a.product_num as productNum, a.product_id as productId, b.market_price as price, c.primary_pic_url as goodsImg')
            ->alias('a')
            ->join('em_goods_product b', 'a.product_id = b.id', 'LEFT')
            ->join('em_goods c', 'b.goods_id = c.id', 'LEFT')
            ->where('a.id', 'in', explode(',', $ids))
            ->select();
        return $list;
    }
}